package ace.module.oauth2.server.test.core.controller;

import ace.cmp.json.api.JsonService;
import ace.module.oauth2.callback.contract.feign.Oauth2AceAuthenticationCallbackFeign;
import ace.module.oauth2.server.api.callback.model.input.Oauth2AceAuthenticationCallbackInput;
import ace.module.oauth2.server.api.enums.Oauth2RegisteredClientAuthConfigAuthenticationTypeEnum;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceAuthResultDetailDto;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceAuthResultDto;
import ace.module.oauth2.server.core.impl.properties.Oauth2ServerSecurityProperties;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author caspar
 * @date 2023/2/14 10:58
 */
@RequestMapping("/account/oauth2/rpc")
@RestController
@AllArgsConstructor
public class Oauth2AceAuthenticationCallbackTestController implements Oauth2AceAuthenticationCallbackFeign {

  private final Oauth2ServerSecurityProperties properties;
  private final JsonService jsonService;
  public static String DEFAULT_USERNAME = "username";
  public static String DEFAULT_EXTERNAL_USER_ACCOUNT_ID = "defaultAccountId";

  @Override
  public Oauth2AceAuthResultDto authentication(Oauth2AceAuthenticationCallbackInput input) {

    String failFlag = Optional.ofNullable(input)
        .map(Oauth2AceAuthenticationCallbackInput::getBizParams)
        .map(p -> (String) p.get("failFlag"))
        .orElse("false");

    if (Oauth2RegisteredClientAuthConfigAuthenticationTypeEnum.USERNAME.getCode().equals(input.getAuthType())) {
      String username = Optional.ofNullable(input)
          .map(Oauth2AceAuthenticationCallbackInput::getBizParams)
          .map(p -> (String) p.get("username"))
          .orElse("");
      if (StringUtils.equals(username, DEFAULT_USERNAME)) {
        Oauth2AceAuthResultDetailDto output = jsonService.toObject(properties.getLoginByGrantTypeOutputJson(), Oauth2AceAuthResultDetailDto.class);
        Oauth2AceAuthResultDto dto = new Oauth2AceAuthResultDto();
        dto.setCode(0);
        dto.setData(output);
        return dto;
      } else {
        Oauth2AceAuthResultDto dto = new Oauth2AceAuthResultDto();
        dto.setCode(1);
        dto.setMessage("账户或密码错误");
        return dto;
      }
    } else {
      Oauth2AceAuthResultDetailDto output = jsonService.toObject(properties.getLoginByGrantTypeOutputJson(), Oauth2AceAuthResultDetailDto.class);
      Oauth2AceAuthResultDto dto = new Oauth2AceAuthResultDto();
      dto.setCode(0);
      dto.setData(output);
      return dto;
    }
  }
}
